package cn.hy.util;

import cn.hy.constants.LoginConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;

/**
 * JWT工具类
 */
public class JwtTokenUtils {

    /**
     * 生成足够的安全随机密钥，以适合符合规范的签名
     */
    private static final byte[] API_KEY_SECRET_BYTES = DatatypeConverter.parseBase64Binary(LoginConstants.JWT_SECRET_KEY);
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(API_KEY_SECRET_BYTES);

    public static String createToken(String username, String id) {
        long expiration = LoginConstants.EXPIRATION;
        final Date createdDate = new Date();
        final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);
        String token = Jwts.builder()
                .setHeaderParam("type", LoginConstants.TOKEN)
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                // 自定义信息
                //.claim(SecurityConstants.ROLE_CLAIMS, String.join(",", roles))
                .setId(id) // 主键
                .setIssuer("hy")
                .setIssuedAt(createdDate)
                .setSubject(username)
                .setExpiration(expirationDate)
                .compact();
        return token;
    }

    public static String getId(String token) {
        Claims claims = getClaims(token);
        return claims.getId();
    }


    private static Claims getClaims(String token) {
        return Jwts.parserBuilder().setSigningKey(SECRET_KEY).build().parseClaimsJws(token).getBody();
    }

}
